import { pick } from "lodash-es";
import type { CSSProperties } from "react";
import { useMemo } from "react";
import "../style/SvgIcon.less";

interface PropType {
	prefix?: string;
	name: string;
	size?: number | string;
	spin?: boolean;
	onClick?: Fn;
}
const SvgIcon = (props: PropType) => {
	// fix React18 "defaultProps" problem
	props = Object.assign({}, { prefix: "icon", size: 16, spin: false, ...props });

	const attrs = pick(props, ["className", "style"]) as Recordable<{ className: string; style: Object }>;
	const prefixCls = "svg-icon";
	const symbolId = useMemo(() => `#${props.prefix}-${props.name}`, [props.prefix, props.name]);

	const getAttrsClass = useMemo(() => {
		let classList = [prefixCls, attrs.className];
		if (props.spin) classList.push("svg-icon-spin");
		return classList.join(" ");
	}, [props.spin, attrs]);

	const getStyle = useMemo((): CSSProperties => {
		const { size } = props;
		let s = `${size}`;
		s = `${s.replace("px", "")}px`;
		return {
			width: s,
			height: s
		};
	}, [props.size]);

	return (
		<svg className={getAttrsClass} style={getStyle} aria-hidden="true" onClick={props.onClick}>
			<use xlinkHref={symbolId} />
		</svg>
	);
};

export default SvgIcon;
